import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/models/store_product_query.dart';
import 'package:fsharing/core/models/store_search.dart';
import 'package:fsharing/core/viewmodels/pages/home/search_model.dart';
import 'package:fsharing/core/viewmodels/pages/home/search_store_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/main.dart';
import 'package:fsharing/ui/pages/store/product_page.dart';
import 'package:fsharing/ui/pages/store/store_page.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SearchStorePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProxyProvider<SearchModel, SearchStoreModel>(
      create: (context) => SearchStoreModel(Provider.of(context, listen: false)),
      update: (context, searchModel, model) => model..keyword = searchModel.keyword,
      child: Consumer<SearchStoreModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Center(
                child: CircularProgressIndicator(),
              );
            case ViewState.error:
              return Center(
                child: Text(model.errorMessage),
              );
            case ViewState.success:
              return _SuccessWidget();
            default:
              return Container();
          }
        },
      ),
    );
  }
}

class _SuccessWidget extends StatelessWidget {
  final RefreshController _refreshController = RefreshController();

  @override
  Widget build(BuildContext context) {
    SearchStoreModel model = Provider.of(context, listen: false);
    List<Store> list = model.list;
    StoreSearch storeSearch = model.storeSearch;
    return Theme(
      data: lightTheme(),
      child: Material(
        child: SmartRefresher(
          controller: _refreshController,
          child: ListView.separated(
            padding: EdgeInsets.all(20),
            itemBuilder: (context, index) {
              return _StoreItemWidget(
                store: list[index],
              );
            },
            separatorBuilder: (context, index) {
              return Divider(
                height: 32,
              );
            },
            itemCount: list.length,
          ),
          enablePullDown: false,
          enablePullUp: storeSearch.models.content.length == 10,
          onLoading: () => _onLoadData(context),
        ),
      ),
    );
  }

  void _onLoadData(BuildContext context) async {
    SearchStoreModel model = Provider.of(context, listen: false);
    await model.loadData();
    _refreshController.loadComplete();
  }
}

class _StoreItemWidget extends StatelessWidget {
  final Store store;

  _StoreItemWidget({
    Key key,
    @required this.store,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: CachedNetworkImage(
                imageUrl: store.logoUrl,
                width: 40,
                height: 40,
                fit: BoxFit.fill,
              ),
            ),
            Expanded(
              child: Container(
                height: 40,
                margin: EdgeInsets.only(left: 8),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      store.name,
                      style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
                    ),
                    Text(
                      store.levelText,
                      style: TextStyle(
                        color: Colors.grey,
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                      ),
                    )
                  ],
                ),
              ),
            ),
            Container(
              width: 64,
              height: 24,
              child: OutlineButton(
                onPressed: () {
                  _onItemClicked(context);
                },
                textColor: Theme.of(context).accentColor,
                borderSide: BorderSide(color: Theme.of(context).accentColor),
                child: Text(
                  '进店',
                  style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
                ),
              ),
            ),
          ],
        ),
        Container(
          height: 105,
          margin: EdgeInsets.only(top: 16),
          child: ListView.separated(
            scrollDirection: Axis.horizontal,
            itemBuilder: (context, index) {
              return _ProductItemWidget(
                product: store.topProducts[index],
              );
            },
            separatorBuilder: (context, index) {
              return VerticalDivider(
                width: 8,
                color: Colors.transparent,
              );
            },
            itemCount: store.topProducts.length,
          ),
        )
      ],
    );
  }

  void _onItemClicked(BuildContext context) {
    Navigator.of(context).pushNamed('/store', arguments: StorePageArgs(store.id, 0));
  }
}

class _ProductItemWidget extends StatelessWidget {
  final Product product;

  _ProductItemWidget({
    Key key,
    @required this.product,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Stack(
        alignment: Alignment.bottomLeft,
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: CachedNetworkImage(
              imageUrl: product.productImage,
              width: 105,
              height: 105,
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(vertical: 2, horizontal: 8),
            decoration: BoxDecoration(
              color: Colors.black38,
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(4),
                topRight: Radius.circular(4),
              ),
            ),
            child: Text(
              '￥${product.sellingPrice}',
              style: TextStyle(color: Colors.white),
            ),
          )
        ],
      ),
      onTap: () {
        _onItemClicked(context);
      },
    );
  }

  void _onItemClicked(BuildContext context) {
    Navigator.of(context).pushNamed(
      '/product',
      arguments: ProductPageArgs(product.miaId, product.curStoreId),
    );
  }
}
